/**
 * 二维码生成工具
 * @author 王勇程 <laughskydragon@qq.com>
 */

// 简化版二维码生成器（适用于uni-app）
class QRCodeGenerator {
  constructor() {
    this.modules = []
    this.moduleCount = 0
  }

  // 生成二维码到Canvas
  static toCanvas(ctx, text, options = {}, callback) {
    const qr = new QRCodeGenerator()
    const opts = {
      width: options.width || 200,
      height: options.height || 200,
      margin: options.margin || 2,
      color: {
        dark: options.color?.dark || '#000000',
        light: options.color?.light || '#FFFFFF'
      },
      ...options
    }

    try {
      // 生成二维码数据
      qr.make(text)
      
      // 绘制到Canvas
      qr.drawCanvas(ctx, opts)
      
      if (callback) {
        callback(null)
      }
    } catch (error) {
      if (callback) {
        callback(error)
      }
    }
  }

  // 简化的二维码生成算法
  make(text) {
    // 这里使用简化的算法生成二维码模式
    // 实际项目中建议使用专业的二维码库如 qrcode.js
    
    const size = this.getSize(text.length)
    this.moduleCount = size
    this.modules = []
    
    // 初始化模块数组
    for (let row = 0; row < size; row++) {
      this.modules[row] = []
      for (let col = 0; col < size; col++) {
        this.modules[row][col] = false
      }
    }
    
    // 添加定位图案
    this.addPositionDetectionPattern(0, 0)
    this.addPositionDetectionPattern(size - 7, 0)
    this.addPositionDetectionPattern(0, size - 7)
    
    // 添加分隔符
    this.addSeparator(0, 0)
    this.addSeparator(size - 7, 0)
    this.addSeparator(0, size - 7)
    
    // 添加时序图案
    this.addTimingPattern()
    
    // 添加数据（简化版）
    this.addData(text)
  }

  // 根据文本长度确定二维码大小
  getSize(textLength) {
    if (textLength <= 20) return 21
    if (textLength <= 40) return 25
    if (textLength <= 60) return 29
    return 33
  }

  // 添加定位图案
  addPositionDetectionPattern(x, y) {
    for (let r = -1; r <= 7; r++) {
      for (let c = -1; c <= 7; c++) {
        const row = y + r
        const col = x + c
        
        if (row >= 0 && row < this.moduleCount && col >= 0 && col < this.moduleCount) {
          if ((0 <= r && r <= 6 && (c === 0 || c === 6)) ||
              (0 <= c && c <= 6 && (r === 0 || r === 6)) ||
              (2 <= r && r <= 4 && 2 <= c && c <= 4)) {
            this.modules[row][col] = true
          } else {
            this.modules[row][col] = false
          }
        }
      }
    }
  }

  // 添加分隔符
  addSeparator(x, y) {
    for (let r = -1; r <= 7; r++) {
      for (let c = -1; c <= 7; c++) {
        const row = y + r
        const col = x + c
        
        if (row >= 0 && row < this.moduleCount && col >= 0 && col < this.moduleCount) {
          if (r === -1 || r === 7 || c === -1 || c === 7) {
            this.modules[row][col] = false
          }
        }
      }
    }
  }

  // 添加时序图案
  addTimingPattern() {
    for (let i = 8; i < this.moduleCount - 8; i++) {
      this.modules[6][i] = i % 2 === 0
      this.modules[i][6] = i % 2 === 0
    }
  }

  // 添加数据（简化版）
  addData(text) {
    // 简化的数据填充算法
    const hash = this.simpleHash(text)
    let bitIndex = 0
    
    // 从右下角开始填充数据
    for (let col = this.moduleCount - 1; col > 0; col -= 2) {
      if (col === 6) col-- // 跳过时序列
      
      for (let row = 0; row < this.moduleCount; row++) {
        for (let c = 0; c < 2; c++) {
          const currentCol = col - c
          const currentRow = (col + 1) % 4 < 2 ? row : this.moduleCount - 1 - row
          
          if (currentRow >= 0 && currentRow < this.moduleCount && 
              currentCol >= 0 && currentCol < this.moduleCount) {
            
            // 跳过功能图案
            if (!this.isFunctionModule(currentRow, currentCol)) {
              const bit = (hash >> (bitIndex % 32)) & 1
              this.modules[currentRow][currentCol] = bit === 1
              bitIndex++
            }
          }
        }
      }
    }
  }

  // 简单哈希函数
  simpleHash(text) {
    let hash = 0
    for (let i = 0; i < text.length; i++) {
      const char = text.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash // 转换为32位整数
    }
    return Math.abs(hash)
  }

  // 检查是否为功能模块
  isFunctionModule(row, col) {
    // 定位图案
    if ((row < 9 && col < 9) || 
        (row < 9 && col >= this.moduleCount - 8) ||
        (row >= this.moduleCount - 8 && col < 9)) {
      return true
    }
    
    // 时序图案
    if (row === 6 || col === 6) {
      return true
    }
    
    return false
  }

  // 绘制到Canvas
  drawCanvas(ctx, options) {
    const { width, height, margin, color } = options
    const moduleSize = Math.floor((width - margin * 2) / this.moduleCount)
    const offsetX = Math.floor((width - moduleSize * this.moduleCount) / 2)
    const offsetY = Math.floor((height - moduleSize * this.moduleCount) / 2)

    // 清空画布
    ctx.clearRect(0, 0, width, height)
    
    // 绘制背景
    ctx.setFillStyle(color.light)
    ctx.fillRect(0, 0, width, height)
    
    // 绘制二维码模块
    ctx.setFillStyle(color.dark)
    for (let row = 0; row < this.moduleCount; row++) {
      for (let col = 0; col < this.moduleCount; col++) {
        if (this.modules[row][col]) {
          const x = offsetX + col * moduleSize
          const y = offsetY + row * moduleSize
          ctx.fillRect(x, y, moduleSize, moduleSize)
        }
      }
    }
  }
}

// 导出
export default QRCodeGenerator